﻿using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Xml;
using todo.Model;

namespace todo.Persistence
{
    public class TodoListParser
    {
        public static TodoList Parse(string fileName)
        {
            string inEl = null;
            try
            {
                if (new FileInfo(fileName).Length < 1)
                {
                    return null;
                }
            }
            catch (FileNotFoundException e)
            {
                return null;
            }
            var todoList = new TodoList();
            using (var reader = XmlReader.Create(fileName))
            {
                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element:
                            var name = reader.Name;
                            if (name == "todolist")
                            {
                                todoList.Id = reader.GetAttribute("id");
                            }
                            else if(name == "todos")
                            {
                                //fast return
                                return todoList;
                            }
                            else
                            {
                                inEl = name;
                            }
                            break;
                        case XmlNodeType.Text:
                            if (inEl == "updateTime")
                            {
                                try
                                {
                                    todoList.UpdateTime = DateTime.ParseExact(reader.Value,
                                            "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                                }
                                catch (Exception e)
                                {
                                    Debug.Print("err: " + e.Message);
                                }

                            }
                            break;

                        case XmlNodeType.EndElement:

                            break;
                    }
                }
            }
            return null;
        }
    }
}